"use client";
import GlobalNotify from "@/components/ModalPopup/GlobalNotifyModal";

import {
    doClaimShopApi,
    getShopInfoApi,
    ShopActivityRewardItem,
    ShopInfo,
    ShopProductItem,
} from "@/api/depositsApi";
import { BtnTypeEnum, BtnTypeMap, ClaimActiveErrorMap } from "@/enums";
import { useRouter } from "@/i18n/routing";
import { formatAmount } from "@/utils/index";
import { Toast } from "antd-mobile";
import clsx from "clsx";
import { useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import React from "react";
import "swiper/css/pagination";
import { Pagination } from "swiper/modules";
import { Swiper, SwiperClass, SwiperSlide } from "swiper/react";
import styles from "./page.module.scss";

const CardPage = () => {
    const router = useRouter();
    const searchParams = useSearchParams();
    const swiperRef = React.useRef<SwiperClass | null>(null);

    const [act, setAct] = React.useState(0);
    const [amount, setAmount] = React.useState<any>({});
    const [visible, setVisible] = React.useState<boolean>(false);
    const [shopInfo, setShopInfo] = React.useState<ShopInfo>({} as ShopInfo);
    const [loading, setLoading] = React.useState(false);
    const [canClaim, setCanClaim] = React.useState<number[]>([]);

    const shop_id = React.useMemo(() => {
        return Number(searchParams.get("shop_id"));
    }, []);
    const t = useTranslations();

    React.useEffect(() => {
        getInfo();
    }, []);

    const getInfo = async () => {
        if (!shop_id) {
            setShopInfo({} as ShopInfo);
            return;
        }
        try {
            setLoading(true);
            const res = await getShopInfoApi({ shop_id });

            if (res?.code === 200 && res?.data?.products) {
                let actKey = 0;
                let canClaimArray: number[] = [];
                res.data.products.sort((a: any, b: any) => {
                    return a.pay - b.pay;
                });

                const result = res.data.products.map((item: ShopProductItem, idx: number) => {
                    item.btnType = BtnTypeEnum.DISABLED;
                    //|| item.is_suss === -1
                    if (item.days <= 0) {
                        item.btnType = BtnTypeEnum.DEPOSITE;
                    }
                    if (item.days > 0 && item.is_suss === 0) {
                        canClaimArray.push(idx);
                        if (!actKey) {
                            actKey = idx;
                        }
                    }

                    if (item.days > 0 && item.is_suss === 0) {
                        item.btnType = BtnTypeEnum.CANCLAIM;
                    }

                    return item;
                });

                //自动滚动到第一个买了的商品
                setTimeout(() => {
                    if (actKey) {
                        setAct(actKey);
                    }
                    swiperRef.current?.slideToLoop(actKey, 0, false);
                }, 100);

                setCanClaim(canClaimArray);
                setShopInfo({ ...res.data, products: result || [] });
            }
        } finally {
            setLoading(false);
        }
    };

    const doChange = (type: 1 | -1) => {
        if (swiperRef.current) {
            if (type === 1) swiperRef.current.slideNext();
            if (type === -1) swiperRef.current.slidePrev();
        }
    };
    const redPointInfo = React.useMemo(() => {
        const min = Math.min(...canClaim);
        const max = Math.max(...canClaim);
        const result = {
            prev: false,
            next: false,
        };
        if (act > min) {
            result.prev = true;
        }
        if (act < max) {
            result.next = true;
        }
        return result;
    }, [act]);

    // const data = React.useMemo(() => {
    //     return [1, 2, 3, 4, 5];
    // }, []);

    const getActiveInfo = (itemData: ShopProductItem) => {
        const amountInfo = itemData.activity_reward.find((item: ShopActivityRewardItem) => {
            return item.item_id === 1;
        });
        const boundsInfo = itemData.activity_reward.find((item: ShopActivityRewardItem) => {
            return item.item_id === 2;
        });
        const bounsAmount = boundsInfo?.amount || 0;
        const bounsValue =
            boundsInfo?.reward === 1 ? bounsAmount : (bounsAmount / 100) * itemData.pay_value;
        const amountAmount = amountInfo?.amount || 0;
        const amountValue =
            amountInfo?.reward === 1 ? amountAmount : (amountAmount / 100) * itemData.pay_value;
        return {
            amount: amountValue,
            amountRollover: amountInfo?.rollover || 0,
            bouns: bounsValue,
            bounsRollover: boundsInfo?.rollover || 0,
        };
    };

    const doClaim = async (itemData: ShopProductItem) => {
        if (!itemData.id) {
            Toast.show({ content: "Missing product ID" });
            return;
        }
        if (itemData.btnType === BtnTypeEnum.DEPOSITE) {
            router.push(`/deposit?target_id=${shop_id}`);
            return;
        }
        if (itemData.btnType !== BtnTypeEnum.CANCLAIM) {
            return;
        }
        try {
            const res = await doClaimShopApi({
                id: itemData.id,
            });

            if (res.code === 200 && res?.data?.code === 1) {
                const amountObj: any = {};
                if (res?.data?.reward) {
                    res?.data?.reward.forEach((item: any) => {
                        amountObj[`coin_${item.coin_type}`] = formatAmount(item.amount);
                    });
                }
                if (res?.data?.extra_reward) {
                    res?.data?.extra_reward.forEach((item: any) => {
                        amountObj[`coin_${item.coin_type}`] = formatAmount(
                            new BigNumber(amountObj[`coin_${item.coin_type}`] || 0)
                                .plus(item.amount)
                                .toString()
                        );
                    });
                }
                setAmount(amountObj);
                setVisible(true);
                getInfo();
            } else {
                throw new Error(ClaimActiveErrorMap.get(res.data.code) || t(`code.400`));
            }
        } catch (error: any) {
            if (error) {
                Toast.show({
                    content: error.message || error.toString(),
                    maskClickable: false,
                });
            }
        }
    };

    return (
        <div className={styles.CardPage}>
            <div className={styles.top} style={{ minHeight: "300px" }}>
                <Swiper
                    spaceBetween={10}
                    slidesPerView={1.25}
                    centeredSlides={true}
                    onSwiper={(swiper) => {
                        swiperRef.current = swiper;
                    }}
                    onSlideChange={(swiper) => {
                        setAct(swiper.realIndex);
                    }}
                    loop={shopInfo?.products?.length > 3 || false}
                    modules={[Pagination]}
                    // loopAdditionalSlides={2}
                    pagination={{
                        clickable: true,
                    }}
                >
                    {!!shopInfo?.products?.length &&
                        shopInfo?.products.map((item) => {
                            const itemInfo = getActiveInfo(item);
                            return (
                                <SwiperSlide
                                    key={item.id}
                                    className={clsx(styles.swiperSlide, {
                                        [styles.swiperSlideBlue]: item.style === 1,
                                        [styles.swiperSlideGold]: item.style === 3,
                                    })}
                                >
                                    <div className={styles.swiperItem}>
                                        <div
                                            className={clsx(
                                                "flex flex-row items-center justify-between",
                                                styles.swiperItemTop
                                            )}
                                        >
                                            <div className={clsx(styles.leftContent, "pl-[.1rem]")}>
                                                {shop_id === 4 && "CARTãO DE MêS"}
                                                {shop_id === 3 && "Cartão Semanal"}
                                            </div>
                                            <div
                                                className={clsx(
                                                    styles.rightContent,
                                                    "rounded-[0_.15rem_0_.15rem] pr-[.12rem] pt-[.02rem] text-[.1rem]"
                                                )}
                                            >
                                                {item.days > 0 && "Já foi comprado"}
                                            </div>
                                        </div>
                                        <div className={styles.cardContainerOut}>
                                            <div className={styles.cardContent}>
                                                <div className={styles.cardLeft}>
                                                    <div>
                                                        <div
                                                            className={clsx(
                                                                "text-[.11rem] font-bold"
                                                            )}
                                                        >
                                                            Para Recarregar
                                                        </div>
                                                        <div
                                                            className={clsx(
                                                                "my-[.04rem] text-[.30rem] font-bold",
                                                                styles.money
                                                            )}
                                                        >
                                                            {item.pay_value}R
                                                        </div>
                                                    </div>
                                                    <div className="pb-[.2rem] text-[.15rem] font-bold">
                                                        EXTRA {item.desc}%
                                                    </div>
                                                </div>
                                                <div className={styles.cardRight}>
                                                    <div
                                                        className={clsx(
                                                            "text-[.1rem]",
                                                            styles.cardRightTitle
                                                        )}
                                                    >
                                                        Receba por dia
                                                    </div>
                                                    <div className="flex-1 text-[.1rem]">
                                                        <div className={styles.text_1}>
                                                            Numerário
                                                        </div>
                                                        <div
                                                            className={clsx(
                                                                "text-[.14rem] font-bold",
                                                                styles.text_2
                                                            )}
                                                        >
                                                            {itemInfo.amount}R
                                                        </div>
                                                    </div>
                                                    <div className="flex-1 text-[.1rem]">
                                                        <div className={styles.text_1}>Bônus</div>
                                                        <div
                                                            className={clsx(
                                                                "text-[.14rem] font-bold",
                                                                styles.text_2
                                                            )}
                                                        >
                                                            {itemInfo.bouns}R
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className={styles.rili}>
                                                    <div className={styles.riliContent}>
                                                        <div className="text-[.14rem] font-bold text-[#ac4b31]">
                                                            {shop_id === 4 ? "30" : ""}
                                                            {shop_id === 3 ? "7" : ""}
                                                        </div>
                                                        <div className="text-[.12rem] text-[#ac4b31]">
                                                            dias
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div className={styles.lingqu}>
                                                <div
                                                    className={clsx(
                                                        styles.lingquTop,
                                                        "text-[.15rem] font-bold text-[#e4292d]"
                                                    )}
                                                >
                                                    Receba por dia
                                                </div>
                                                <div className={clsx(styles.lingquContent)}>
                                                    <div className={clsx(styles.lingquInfo)}>
                                                        {item.btnType === BtnTypeEnum.DEPOSITE && (
                                                            <>
                                                                <div className="text-center text-[.16rem] font-bold text-[#fffc03]">
                                                                    Você ainda não comprou
                                                                </div>
                                                                <div
                                                                    className={styles.btn2}
                                                                    onClick={() => doClaim(item)}
                                                                >
                                                                    {BtnTypeMap.get(item.btnType)}
                                                                </div>
                                                            </>
                                                        )}
                                                        {item.btnType !== BtnTypeEnum.DEPOSITE && (
                                                            <>
                                                                <div
                                                                    className={clsx(
                                                                        "text-[.18rem] font-bold",
                                                                        styles.receiveText
                                                                    )}
                                                                >
                                                                    NUMERÁRIO {itemInfo.amount}R
                                                                </div>
                                                                <div
                                                                    className={clsx(
                                                                        "text-[.18rem]",
                                                                        styles.receiveText
                                                                    )}
                                                                >
                                                                    +
                                                                </div>
                                                                <div
                                                                    className={clsx(
                                                                        "text-[.18rem] font-bold",
                                                                        styles.receiveText
                                                                    )}
                                                                >
                                                                    BÔNUS {itemInfo.bouns}R
                                                                </div>
                                                                <div
                                                                    className={clsx(
                                                                        "mt-[.08rem] text-[.18rem] font-bold",
                                                                        styles.receiveText2
                                                                    )}
                                                                >
                                                                    {item.days} DIAS RESTANTES
                                                                </div>
                                                                <div
                                                                    className={clsx(styles.btn, {
                                                                        [styles.disabled]:
                                                                            item.btnType ===
                                                                            BtnTypeEnum.DISABLED,
                                                                    })}
                                                                    onClick={() => doClaim(item)}
                                                                >
                                                                    {item.btnType != undefined &&
                                                                        BtnTypeMap.get(
                                                                            item.btnType
                                                                        )}
                                                                </div>
                                                            </>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </SwiperSlide>
                            );
                        })}
                </Swiper>
                <div className={styles.pagation}>
                    <div
                        className={clsx(styles.arrow, styles.arrowLeft)}
                        onClick={() => doChange(-1)}
                    >
                        <i className="iconfont icon-xiangyou1"></i>
                        {redPointInfo.prev && <div className={styles.redCircle}></div>}
                    </div>

                    <div
                        className={clsx(styles.arrow, styles.arrowRight)}
                        onClick={() => doChange(1)}
                    >
                        <i className="iconfont icon-xiangyou1"></i>
                        {redPointInfo.next && <div className={styles.redCircle}></div>}
                    </div>
                </div>
            </div>
            <div className={styles.main}>
                <div
                    className="my-[.15rem] cursor-pointer text-right text-[#12cc60]"
                    onClick={() => router.push(`/cardRecord?shop_id=${shop_id}`)}
                >
                    Receba sens registros&gt;
                </div>
                <div className={styles.config}>
                    <div className={clsx(styles.configItem, "bg-[#2e3438]")}>
                        <div>Recarga</div>
                        <div>Receba dinheiro diariamente</div>
                        <div>Receba seu bônus diarianente</div>
                        <div>Taxa de retirada de dinheiro</div>
                        <div>Bônus retirada nultiplicação</div>
                    </div>
                    {shopInfo?.products?.map((item) => {
                        const itemInfo = getActiveInfo(item);
                        return (
                            <div key={item.id} className={styles.configItem}>
                                <div>{item.pay_value}</div>
                                <div>{itemInfo.amount}</div>
                                <div>{itemInfo.bouns}</div>
                                <div>{itemInfo.amountRollover}</div>
                                <div>{itemInfo.bounsRollover}</div>
                            </div>
                        );
                    })}
                </div>
                <div className={styles.introbox}>
                    <div className={styles.introContainer}>
                        <div className={styles.introTitle}>
                            <span className={styles.introTitleText}>Regras de Atividade</span>
                        </div>
                        <ul className={styles.introboxDesc}>
                            <li>
                                Recarregue no dia 1 e receba bônus + prêmios emdinheiro diariamente
                                do mesmo dia até o dia {shop_id === 3 ? "7" : "30"}.
                            </li>
                            <li>A retirada diária do prémio do cartão mensal é até às 23h30.</li>
                            <li>0 cartão mensal é recolhido 1 vez por dia.</li>
                            <li>
                                Reemissão automática da parte do prêmio em dinheiro seo cartão
                                mensal não for recebido no dia, o prêmio de ourocolorido não está
                                disponível
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <GlobalNotify
                amount={amount}
                visible={visible}
                onChange={() => setVisible(false)}
                deraction={5000}
            ></GlobalNotify>
        </div>
    );
};

export default CardPage;
CardPage;
